﻿using Alipay.AopSdk.Core.Domain;
using SmartWMS.Common.Extensions;
using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.BasicsDatum;
using SmartWMS.Domain.BusinessManage;
using SmartWMS.Domain.FinanceManage;
using SmartWMS.EntityFramework;
using SmartWMS.Server.BusinessServer.SalesReturns.Dto;
using SmartWMS.Server.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using static SmartWMS.Server.BusinessServer.SalesReturns.SalesReturns;

namespace SmartWMS.Server.BusinessServer.SalesReturns
{
    /// <summary>
    /// 采购退货服务层
    /// </summary>
    public class SalesReturns : ISalesReturns
    {
        /// <summary>
        /// 产品表
        /// </summary>
        private readonly IRepository<Domain.BasicsDatum.Product> _product;
        /// <summary>
        /// 采购产品关联表
        /// </summary>
        private readonly IRepository<Shopping> _shopping;
        /// <summary>
        /// 采购管理表
        /// </summary>
        private readonly IRepository<ProcureManagement> _procureManagement;
        /// <summary>
        /// 采购退货表
        /// </summary>
        private readonly IRepository<ProcuremenReturn> _procuremenReturn;
        /// <summary>
        /// 应收表
        /// </summary>
        private readonly IRepository<Collection> _collection;
        /// <summary>
        /// 供应商表
        /// </summary>
        private readonly IRepository<Supplier> _supplier;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="supplier"></param>
        /// <param name="collection"></param>
        /// <param name="product"></param>
        /// <param name="shopping"></param>
        /// <param name="procureManagement"></param>
        /// <param name="procuremenReturn"></param>
        public SalesReturns(IRepository<Supplier> supplier, IRepository<Collection> collection, IRepository<Domain.BasicsDatum.Product> product, IRepository<Shopping> shopping, IRepository<ProcureManagement> procureManagement, IRepository<ProcuremenReturn> procuremenReturn)
        {
            _supplier = supplier;
            _collection = collection;
            _product = product;
            _shopping = shopping;
            _procureManagement = procureManagement;
            _procuremenReturn = procuremenReturn;
        }

        /// <summary>
        /// 添加应收管理
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddCollection(PaymentDto input)
        {
            try
            {

                //采购退货表
                var ProcuremenReturnList = await _procuremenReturn.GetAllListAsync();
                //采购产品关联表
                var shoppingList = await _shopping.GetAllListAsync();
                //采购管理表
                var ProcureManagementList = await _procureManagement.GetAllListAsync();
                //产品表
                var ProductList = await _product.GetAllListAsync();
                //供应商表
                var SupplierList = await _supplier.GetAllListAsync();
                //四表联查
                var list = (from cg in ProcureManagementList
                            join cgt in ProcuremenReturnList
                            on cg.ProcurementCode equals cgt.ProcurementCode
                            join cgc in shoppingList on cg.ProcurementCode
                            equals cgc.ProcuremenCode
                            join cp in ProductList on cgc.ProductId equals cp.Id
                            join gys in SupplierList on cg.SupplierCode equals gys.SupplierCode
                            where cgt.Id == input.Id
                            select new ProcuremenReturnInfo
                            {
                                Cid = cp.Id,
                                Id = cgt.Id,
                                SalesReturnCode = cg.ProcurementCode,
                                ClientName = cg.ClientName,
                                DocumentType = cg.DocumentType,
                                ProcurementCode = cg.ProcurementCode,
                                UsreName = cgt.UsreName,
                                UserTime = cgt.UserTime,
                                ContactName = cg.ContactName,
                                SupplierCode = cg.SupplierCode,
                                SupplierName = gys.SupplierName,
                                Phone = cg.Phone,
                                Remark = cg.Remark,
                                ProductCode = cp.ProductCode,
                                ProductName = cp.ProductName,
                                Specs = cp.Specs,
                                PackageType = cp.PackageType,
                                Inventory = cp.Inventory,
                                ReturnNumber = cgt.ReturnNumber,
                                Price = cp.Price,
                                ReturnState = cgt.ReturnState,
                                SumPrice = cgt.ReturnNumber * cp.Price,
                            }).FirstDynamic();
                if (list == null)
                {
                    return Response<bool>.Fail(false);
                }
                string YitId = YitIdHelper.NextId().ToString();
                var collection = new Collection();
                collection.Payer = list.ClientName;
                collection.Name = list.ProductName;
                collection.CreateTime = DateTime.Now;
                collection.Receivable = list.SumPrice;
                collection.NetReceipts = list.SumPrice;
                collection.TypeId = 1;
                collection.SerialNumber = YitId;
                collection.Residue = 0;
                collection.PayInstitution = "Apple";
                collection.LastPaymentDate = DateTime.MinValue;
                collection.State = 1;
                collection.Reviewer = "暂无";
                collection.Opinion = "暂无";
                collection.Audittime = DateTime.MinValue;
                collection.Desc = "暂无";
                collection.CreateTime = DateTime.MinValue;

                var result = await _collection.InsertAsync(collection);
                return result > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(false);

            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改审核状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpProcuremenReturnState(ProcuremenReturnInfo input)
        {
            try
            {
                var list = await _procuremenReturn.GetAllListAsync();
                var Sale = list.Where(x => x.Id == input.Id).FirstDynamic();
                Sale.ReturnState = input.ReturnState;
                var result = await _procuremenReturn.UpdateAsync(Sale);
                return result > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(false);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 产品信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<ProcuremenReturnInfo> GetProductProcList(ProcuremenReturnInfo info)
        {
            try
            {
                //采购退货表
                var ProcuremenReturnList = await _procuremenReturn.GetAllListAsync();
                //采购产品关联表
                var shoppingList = await _shopping.GetAllListAsync();
                //采购管理表
                var ProcureManagementList = await _procureManagement.GetAllListAsync();
                //产品表
                var ProductList = await _product.GetAllListAsync();
                //供应商表
                var SupplierList = await _supplier.GetAllListAsync();
                //五表联查
                var list = (from cg in ProcureManagementList
                            join cgt in ProcuremenReturnList
                            on cg.ProcurementCode equals cgt.ProcurementCode
                            join cgc in shoppingList on cg.ProcurementCode
                            equals cgc.ProcuremenCode
                            join cp in ProductList on cgc.ProductId equals cp.Id
                            join gys in SupplierList on cg.SupplierCode equals gys.SupplierCode
                            where cgt.Id == info.Id
                            select new ProcuremenReturnInfo
                            {
                                ClientName = cg.ClientName,
                                Cid = cp.Id,
                                Id = cgt.Id,
                                SalesReturnCode = cg.ProcurementCode,
                                DocumentType = cg.DocumentType,
                                ProcurementCode = cg.ProcurementCode,
                                UsreName = cgt.UsreName,
                                UserTime = cgt.UserTime,
                                ContactName = cg.ContactName,
                                SupplierCode = cg.SupplierCode,
                                SupplierName = gys.SupplierName,
                                Phone = cg.Phone,
                                Remark = cg.Remark,
                                ProductCode = cp.ProductCode,
                                ProductName = cp.ProductName,
                                Specs = cp.Specs,
                                PackageType = cp.PackageType,
                                Inventory = cp.Inventory,
                                ReturnNumber = cgt.ReturnNumber,
                                Price = cp.Price,
                                ReturnState = cgt.ReturnState,
                                SumPrice = cgt.ReturnNumber * cp.Price,
                            }).FirstOrDefault();
                return list;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 产品信息列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<List<ProcuremenReturnInfo>> GetProductProcLists(ProcuremenReturnInfo info)
        {
            try
            {
                //采购退货表
                var ProcuremenReturnList = await _procuremenReturn.GetAllListAsync();
                //采购产品关联表
                var shoppingList = await _shopping.GetAllListAsync();
                //采购管理表
                var ProcureManagementList = await _procureManagement.GetAllListAsync();
                //产品表
                var ProductList = await _product.GetAllListAsync();
                //供应商表
                var SupplierList = await _supplier.GetAllListAsync();
                //五表联查
                var list = (from cg in ProcureManagementList
                            join cgt in ProcuremenReturnList
                            on cg.ProcurementCode equals cgt.ProcurementCode
                            join cgc in shoppingList on cg.ProcurementCode
                            equals cgc.ProcuremenCode
                            join cp in ProductList on cgc.ProductId equals cp.Id
                            join gys in SupplierList on cg.SupplierCode equals gys.SupplierCode
                            where cgt.Id == info.Id
                            select new ProcuremenReturnInfo
                            {
                                ClientName = cg.ClientName,
                                Cid = cp.Id,
                                Id = cgt.Id,
                                SalesReturnCode = cg.ProcurementCode,
                                DocumentType = cg.DocumentType,
                                ProcurementCode = cg.ProcurementCode,
                                UsreName = cgt.UsreName,
                                UserTime = cgt.UserTime,
                                ContactName = cg.ContactName,
                                SupplierCode = cg.SupplierCode,
                                SupplierName = gys.SupplierName,
                                Phone = cg.Phone,
                                Remark = cg.Remark,
                                ProductCode = cp.ProductCode,
                                ProductName = cp.ProductName,
                                Specs = cp.Specs,
                                PackageType = cp.PackageType,
                                Inventory = cp.Inventory,
                                ReturnNumber = cgt.ReturnNumber,
                                Price = cp.Price,
                                ReturnState = cgt.ReturnState,
                                SumPrice = cgt.ReturnNumber * cp.Price,
                            }).ToList();
                return list;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 采购退货信息分页查询
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<List<ProcuremenReturnInfo>>> GetPageProductProcList(ProcuremenReturnInfo info)
        {
            try
            {
                //采购退货表
                var ProcuremenReturnList = await _procuremenReturn.GetAllListAsync();
                //采购产品关联表
                var shoppingList = await _shopping.GetAllListAsync();
                //采购管理表
                var ProcureManagementList = await _procureManagement.GetAllListAsync();
                //产品表
                var ProductList = await _product.GetAllListAsync();
                //供应商表
                var SupplierList = await _supplier.GetAllListAsync();
                //五表联查
                var list = (from cg in ProcureManagementList
                            join cgt in ProcuremenReturnList
                            on cg.ProcurementCode equals cgt.ProcurementCode
                            join cgc in shoppingList on cg.ProcurementCode
                            equals cgc.ProcuremenCode
                            join cp in ProductList on cgc.ProductId equals cp.Id
                            join gys in SupplierList on cg.SupplierCode equals gys.SupplierCode
                            select new ProcuremenReturnInfo
                            {
                                Cid = cp.Id,
                                Id = cgt.Id,
                                SalesReturnCode = cg.ProcurementCode,
                                DocumentType = cg.DocumentType,
                                ProcurementCode = cg.ProcurementCode,
                                UsreName = cgt.UsreName,
                                UserTime = cgt.UserTime,
                                ContactName = cg.ContactName,
                                SupplierCode = cg.SupplierCode,
                                SupplierName = gys.SupplierName,
                                Phone = cg.Phone,
                                Remark = cg.Remark,
                                ProductCode = cp.ProductCode,
                                ProductName = cp.ProductName,
                                Specs = cp.Specs,
                                PackageType = cp.PackageType,
                                Inventory = cp.Inventory,
                                ReturnNumber = cgt.ReturnNumber,
                                Price = cp.Price,
                                ReturnState = cgt.ReturnState,
                                SumPrice = cgt.ReturnNumber * cp.Price,
                            }).ToList();
                if (!string.IsNullOrEmpty(info.SalesReturnCode))
                {
                    list = list.Where(x => x.SalesReturnCode.Contains(info.SalesReturnCode)).ToList();
                }
                if (!string.IsNullOrEmpty(info.ProcurementCode))
                {
                    list = list.Where(x => x.ProcurementCode.Contains(info.ProcurementCode)).ToList();
                }
                if (!string.IsNullOrEmpty(info.ProductName))
                {
                    list = list.Where(x => x.ProductName.Contains(info.ProductName)).ToList();
                }
                if (info.ReturnState != 0)
                {
                    list = list.Where(x => x.ReturnState == info.ReturnState).ToList();
                }

                int totalCount = list.Count();
                int pageCount = (int)Math.Ceiling(totalCount / (double)info.pageSize);
                var result = list.Skip((info.pageIndex - 1) * info.pageSize).Take(info.pageSize).ToList();
                return result != null ? Response<List<ProcuremenReturnInfo>>.Ok(result, totalCount, pageCount) : Response<List<ProcuremenReturnInfo>>.Fail("查询失败");
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 批量删除采购退货信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Response<bool>> PlDelProcuremenReturn(List<ProcuremenReturn> input)
        {
            try
            {
                var result = await _procuremenReturn.DeleteAsync(input);
                return result > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(false);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 采购退货删除
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> DelProcuremenReturn(ProcuremenReturnInfo info)
        {
            var procuremenReturn = info.MapTo<ProcuremenReturn>();
            var result = await _procuremenReturn.DeleteByIdAsync(procuremenReturn);
            return result > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(result > 0);

        }
    }
}
